package com.neusoft.bizcore.license.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.util.StringUtils;

public class LinuxServerInfo extends AbstractServerInfo {

    @Override
    protected List<String> getIpAddress() throws Exception {
        List<String> result = null;

        //获取所有网络接口
        final List<InetAddress> inetAddresses = this.getLocalAllInetAddress();

        if ((inetAddresses != null) && (inetAddresses.size() > 0)) {
            result = inetAddresses.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase)
                    .collect(Collectors.toList());
        }

        return result;
    }

    @Override
    protected List<String> getMacAddress() throws Exception {
        List<String> result = null;

        final List<InetAddress> inetAddresses = this.getLocalAllInetAddress();

        if ((inetAddresses != null) && (inetAddresses.size() > 0)) {
            result = inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList());
        }

        return result;
    }

    @Override
    protected String getCPUSerial() throws Exception {
        String serialNumber = "";
        final String[] shell =
                {"/bin/bash", "-c", "dmidecode -t processor | grep 'ID' | awk -F ':' '{print $2}' | head -n 1" };
        final Process process = Runtime.getRuntime().exec(shell);
        process.getOutputStream().close();

        final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        final String line = reader.readLine().trim();
        if (!StringUtils.isEmpty(line)) {
            serialNumber = line;
        }

        reader.close();
        return serialNumber;
    }

    @Override
    protected String getMainBoardSerial() throws Exception {
        String serialNumber = "";
        final String[] shell =
                {"/bin/bash", "-c", "dmidecode | grep 'Serial Number' | awk -F ':' '{print $2}' | head -n 1" };
        final Process process = Runtime.getRuntime().exec(shell);
        process.getOutputStream().close();

        final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        final String line = reader.readLine().trim();
        if (!StringUtils.isEmpty(line)) {
            serialNumber = line;
        }

        reader.close();
        return serialNumber;
    }
}
